package com.example.myapplication2;
//C:\Users\liuzc\Desktop\MyApplication2\app\src\main\java\com\example\myapplication2\ChatAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<String> messages;
    private static final int VIEW_TYPE_USER = 1;
    private static final int VIEW_TYPE_REPLY = 2;

    public ChatAdapter(List<String> messages) {
        this.messages = messages;
    }

    @Override
    public int getItemViewType(int position) {
        // 假设偶数位置是用户消息，奇数位置是回复消息
        return position % 2 == 0 ? VIEW_TYPE_USER : VIEW_TYPE_REPLY;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_USER) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_user, parent, false);
            return new UserMessageViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_reply, parent, false);
            return new ReplyMessageViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        String message = messages.get(position);
        if (holder instanceof UserMessageViewHolder) {
            ((UserMessageViewHolder) holder).tvMessage.setText(message);
        } else if (holder instanceof ReplyMessageViewHolder) {
            ((ReplyMessageViewHolder) holder).tvMessage.setText(message);
        }
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }

    public class UserMessageViewHolder extends RecyclerView.ViewHolder {
        TextView tvMessage;

        public UserMessageViewHolder(View itemView) {
            super(itemView);
            tvMessage = itemView.findViewById(R.id.tvMessage);
        }
    }

    public class ReplyMessageViewHolder extends RecyclerView.ViewHolder {
        TextView tvMessage;

        public ReplyMessageViewHolder(View itemView) {
            super(itemView);
            tvMessage = itemView.findViewById(R.id.tvMessage);
        }
    }
}
